const dayjs = require('dayjs');
/**
 * 时间处理辅助类
 */

/**
 * 格式化时间展示
 * @param {number} timestamp 时间戳
 */
function formatTime(timestamp) {
    if (!timestamp) return '';
    
    const now = Math.floor(dayjs().valueOf() / 1000);
    const diff = now - timestamp;
    
    if (diff < 60) {
        return '刚刚';
    } else if (diff < 3600) {
        return Math.floor(diff / 60) + '分钟前';
    } else if (diff < 86400) {
        return Math.floor(diff / 3600) + '小时前';
    } else if (diff < 2592000) {
        return Math.floor(diff / 86400) + '天前';
    } else {
        const date = dayjs(timestamp * 1000);
        return `${date.year()}-${date.month() + 1}-${date.date()}`;
    }
}

/**
 * 计算剩余时间
 * @param {number} timestamp 目标时间戳
 */
function getRemainTime(timestamp) {
    if (!timestamp) return '';
    
    const now = Math.floor(dayjs().valueOf() / 1000);
    const diff = timestamp - now;
    
    if (diff <= 0) {
        return '已结束';
    }
    
    const days = Math.floor(diff / 86400);
    const hours = Math.floor((diff % 86400) / 3600);
    const minutes = Math.floor((diff % 3600) / 60);
    
    if (days > 0) {
        return `${days}天${hours}时`;
    } else if (hours > 0) {
        return `${hours}时${minutes}分`;
    } else {
        return `${minutes}分钟`;
    }
}

/**
 * 日期格式化
 * @param {Date} date 日期对象
 * @param {string} format 格式
 */
function formatDate(date, format = 'YYYY-MM-DD') {
    if (!date) return '';
    
    const year = date.year();
    const month = date.month() + 1;
    const day = date.date();
    const hour = date.hour();
    const minute = date.minute();
    const second = date.second();
    
    const padZero = (num) => num < 10 ? `0${num}` : num;
    
    return format
        .replace('YYYY', year)
        .replace('MM', padZero(month))
        .replace('DD', padZero(day))
        .replace('HH', padZero(hour))
        .replace('mm', padZero(minute))
        .replace('ss', padZero(second));
}

module.exports = {
    formatTime,
    getRemainTime,
    formatDate
}; 